package cn.net.isir.controller.manager;

import cn.net.isir.entity.*;
import cn.net.isir.service2.*;
import com.alibaba.fastjson.JSON;
import com.alipay.api.response.AlipayOpenAppMiniTemplatemessageSendResponse;
import cn.net.isir.common.ResultObject;
import cn.net.isir.common.TokenManager;
import cn.net.isir.common.config.AlipayConfig;
import cn.net.isir.common.config.WxConfig;
import cn.net.isir.common.pay.alipay.AlipayAPI;
import cn.net.isir.entity.dto.TemplateMsgData;
import cn.net.isir.utils.DateUtils;
import cn.net.isir.utils.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * @author liuxubo
 * @filename ServingManageController.java
 * @package cn.net.isir.controller.manager
 * @email lxb@isir.net.cn
 * @date 2019/01/02
 * @comment 上菜管理
 * @since 1.8
 */
@RestController
@RequestMapping("/serving")
public class ServingManageController {
    //声明日志对象
    private static Logger logger = Logger.getLogger(ServingManageController.class);

    @Resource
    private ShopService shopService;
    @Resource
    private ServingManageService servingManageService;
    @Resource
    private SendTemplateMessageService sendTemplateMessageService;
    @Resource
    private OrderService orderService;
    @Resource
    private WxMinipUserinfoService wxMinipUserinfoService;
    @Resource
    private AlipayMinipUserinfoService alipayMinipUserinfoService;
    @Resource
    private SendTempMsgService sendTempMsgService;

    /**
     * 根据用户查询通知信息
     *
     * @return 通知信息
     */
    @RequestMapping(value = "/listByUser", method = RequestMethod.GET)
    public ResultObject getServingList(HttpServletRequest request) {

        NotifyTask notifyTask = new NotifyTask();
        String pageNo = request.getParameter("pageNo");
        if (StringUtils.isNotBlank(pageNo)) {
            notifyTask.setPageNo(Integer.parseInt(pageNo));
        }
        String pageSize = request.getParameter("pageSize");
        if (StringUtils.isNotBlank(pageSize)) {
            notifyTask.setPageSize(Integer.parseInt(pageSize));
        }
        String shopId = request.getParameter("shopId");
        if (StringUtils.isNotBlank(shopId)) {
            notifyTask.setShopId(shopId);
        }
        String status = request.getParameter("status");
        if (StringUtils.isNotBlank(status)) {
            notifyTask.setPlatformStatus(status);
        }
        String orderNo = request.getParameter("orderNo");
        if (StringUtils.isNotBlank(orderNo)) {
            notifyTask.setOrderNo(orderNo);
        }

        User user = new User();

        List<Shop> shopList;
        if (StringUtils.isBlank(shopId)) {
            user.setQueryUserId(TokenManager.getTokenId());
            shopList = shopService.selectListByUser(user).getList();
        } else {
            Shop shop = shopService.selectByPrimaryKey(shopId);
            shopList = Collections.singletonList(shop);
        }

//        notifyTask.setShopId();
//        notifyTask.setOrderNo();
//        notifyTask.setPlatformStatus();
        if (shopList == null || shopList.size() == 0) {
            return new ResultObject(200, "success", shopList);
        }
        return new ResultObject(200, "success", servingManageService.getNotifyTask(shopList, notifyTask));
    }

    /**
     * 上菜(发送模板消息)
     *
     * @param notifyId 通知id
     * @return 通知结果
     */
    @RequestMapping(value = "/notify/{notifyId}", method = RequestMethod.POST)
    public ResultObject notify(@PathVariable String notifyId) {
        NotifyTask notifyTask = servingManageService.selectByPrimaryKey(notifyId);
        Shop shop = shopService.selectByPrimaryKey(notifyTask.getShopId());
        Order order = orderService.selectByOrderNo(notifyTask.getOrderNo());

        Date servingTime = new Date();

        TemplateMsgData data = new TemplateMsgData();
        data.setShopName(shop.getName());
        data.setSerialNo(order.getSerialNumber());
        data.setServingTime(DateUtils.format(servingTime, "YYYY-MM-dd HH:mm:ss"));
        data.setComment("请到前台取餐");

        //保存发送消息日志
        SendTempMsg msg = new SendTempMsg();
        msg.setNotifyId(notifyId);
        msg.setPushWay("系统通知");
        msg.setContent(data.toTempString().toJSONString());
        msg.setPushTime(servingTime);
        //如果是微信订单
        if (order.getNo().startsWith("W")) {
            WxMinipUserinfo userinfo = new WxMinipUserinfo();
            userinfo.setUnionid(order.getOrderUser());
            userinfo = wxMinipUserinfoService.selectOne(userinfo);
            //发送模板消息
            ResultObject resultObject = sendTemplateMessageService.sendWxTemplateMessageService(
                    userinfo.getOpenid(),
                    WxConfig.getMsgTempId(),
                    notifyTask.getComment(),
                    data.toTempString());//默认是value
            logger.info(JSON.toJSONString(resultObject.toString()));
            //保存发送消息日志
            msg.setPlatform("微信");
            msg.setUserId(userinfo.getOpenid());
            msg.setResult(resultObject.toString());
            sendTempMsgService.insert(msg);
            //返回结果
            if (resultObject.getResult() != 200) {
                return resultObject;
            }
        }
        //如果是支付宝订单
        if (order.getNo().startsWith("A")) {
            AlipayOpenAppMiniTemplatemessageSendResponse response =
                    AlipayAPI.alipayOpenAppMiniTemplatemessageSend(
                            order.getOrderUser(),
                            notifyTask.getComment(),
                            AlipayConfig.getTemp_msg_id(),
                            null,
                            data.toTempString());
            logger.info(JSON.toJSONString(response));
            //保存发送消息日志
            msg.setPlatform("支付宝");
            msg.setUserId(order.getOrderUser());
            msg.setResult(JSON.toJSONString(response));
            sendTempMsgService.insert(msg);
            if (response == null || (!response.isSuccess())) {
                return new ResultObject(500, "fail", null);
            }
        }
        //修改状态
        return new ResultObject(200, "success", servingManageService.notify(notifyId, servingTime));
    }
}
